<template>
  <el-container>
    <el-header>
      <div style="display: flex;flex-direction: row;border-bottom: 1px solid #dcdfe6;min-height: 60px;">
        <a style="font-size: 50px;line-height: 60px;margin-left: 20px;cursor: pointer;"
           href="/">
          首页
        </a>
      </div>
    </el-header>
    <el-main>
      <el-row>
        <el-col :xl="2">
          dd
        </el-col>
        <el-col :xl="4">
          <div class="h-center">
            <div class="h-right-box" v-if="historyVideoList.length>0">
              <div>历史播放</div>
              <el-card class="box-card h-box-card">
                <template v-for="item in historyVideoList">
                  <div class="h-card-div" :key="item.id">
                    <div>
                      <img :src="item.headImg?getHeadImg(item.headImg):require('@/assets/images/noImage.png')"
                           alt="" width="130px">
                    </div>
                    <div><a :href="'/videoPlayer/'+item.id">{{ item.name }}</a></div>
                  </div>
                </template>
              </el-card>
            </div>
          </div>
        </el-col>
        <el-col :xl="12">
          <el-row type="flex" style="flex-direction: column;">
            <div id="mui-player">
              <div slot="nextMedia">
                <svg t="1584686776454" class="icon" viewBox="0 0 1024 1024" version="1.1"
                     xmlns="http://www.w3.org/2000/svg" p-id="1682" width="22" height="22">
                  <path
                    d="M783.14692466 563.21664097L240.85307534 879.55472126c-39.1656664 24.10194914-90.38230866-6.02548665-90.38230865-51.21664226v-632.676158c0-45.19115433 51.21664097-75.31859011 90.38230865-51.21664226l542.29384932 316.33808029c39.1656664 21.08920518 39.1656664 81.34407804 0 102.43328194z"
                    p-id="1683" fill="#ffffff"></path>
                  <path
                    d="M873.52923331 734.94302767c0 42.17841036-39.1656664 78.33133408-90.38230865 78.33133407s-90.38230866-36.15292371-90.38230735-78.33133407V289.05697233c0-42.17841036 39.1656664-78.33133408 90.38230735-78.33133407s90.38230866 36.15292371 90.38230865 78.33133407v445.88605534z"
                    p-id="1684" fill="#ffffff"></path>
                </svg>
              </div>
              <div slot="openToLocal">
                <i class="el-icon-s-promotion" style="color: #FFFFFF;"></i>
              </div>
            </div>
          </el-row>
        </el-col>
        <el-col :xl="4">
          <div>
            <div class="h-right-box">
              <div style="margin-bottom: 10px;">选集</div>
              <div>
                <div v-for="(item,index) in videos" :key="item.sort"
                     :class="item.sort===nowPlayVideo.sort?'h-video-radio-box h-video-radio-box-select':'h-video-radio-box'"
                     @click="startSelectVideo(item.id)">
                  {{ item.videoNumber }}
                </div>
              </div>
            </div>
            <div class="h-right-box" v-if="videoRelation.length>0">
              <div>
                相关番剧
              </div>
              <el-card class="box-card  h-box-card" style="margin-top: 10px;">
                <template v-for="item in videoRelation">
                  <div class="h-card-div" :key="item.id">
                    <div>
                      <img :src="item.headImg?getHeadImg(item.headImg):require('@/assets/images/noImage.png')"
                           alt="" width="130px"></div>
                    <div>
                      <a :href="'/videoPlayer/'+item.id">{{ item.name }}</a>
                    </div>
                  </div>
                </template>
              </el-card>
            </div>
          </div>
          <div>
            <el-upload :action="nowPlayVideo.id"
                       style="display: none;"
                       ref="upload"
                       :http-request="addSubTitle"
                       :show-file-list="false"
                       :multiple="true"
                       :before-upload="subtitleHandlePreview"
                       :auto-upload="true">
              添加字幕
            </el-upload>
          </div>
        </el-col>
        <el-col :xl="2">
          dd
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>
<script>
import MuiPlayer from 'mui-player'
import { getSubtitle, getVideoAllInfo, getVideoFile, subtitleUpload } from '@/api/video/videoFile'
import { addHistory } from '@/api/video/history'
import { Message } from 'element-ui'
import 'mui-player/dist/mui-player.min.css'
import MuiPlayerDesktopPlugin from 'mui-player-desktop-plugin'
import Flv from 'flv.js'
import Hls from 'hls.js'
import { H_Subtitle } from '@/plugins/h_subtitle'
import { getHistoryVideoList } from '@/api/video/video'

export default {
  name: 'videoPlayer',
  data() {
    return {
      historyQueryParams: {
        pageNum: 1,
        pageSize: 5,
        orderByColumn: 'insert_time',
        isAsc: 'desc'
      },
      historyVideoList: [],
      historyTotal: 0,
      player: null,
      nowPlayVideo: {
        id: 'aaaaaaaaaaaaaaaaaa',
        sort: 0
      },
      videos: [],
      //上次保存观看历史的视频对象(里边由播放时间)
      preVideo: {
        id: '',
        preTime: 0
      },
      syncVideoInterval: null,
      //关联番剧
      videoRelation: [],
      subtitle: null,
      font: 'SourceHanSerifCNSemiBold',
      fontMap: {
        SourceHanSerifCNSemiBold: require('@/assets/fonts/SourceHanSerifCN-SemiBold-7.otf')
      }
    }
  },
  created() {
  },
  mounted() {
    let params = this.$route.params.pathMatch
    //番剧id
    let videoId = params.indexOf('/') === -1 ? params : params.substring(0, params.indexOf('/'))
    let videoFileId = params.indexOf('/') === -1 ? null : params.substring(params.indexOf('/') + 1)
    getVideoAllInfo({ videoId, id: videoFileId }).then(res => {
      if (res.code === 200) {
        //播放列表
        this.videos = res.data.videoList
        if (this.videos.length === 0) {
          Message.error('此番剧下无视频')
          return
        }
        this.nowPlayVideo = res.data.videoFile
        this.videoRelation = res.data.videoRelation
        //播放视频 如果是以视频链接进来的,不断点播放
        this.playerLoadVideo(res.data.videoFile, res.data.videoHistory)
      } else {
        Message.error('未找到视频')
      }
    })
    this.getHistoryVideo()
    //控制左右
    let that = this
    document.onkeydown = function(e) {
      let video = that.player.video()
      if (e.code === 'ArrowLeft' && video.currentTime !== 0) {
        video.currentTime = video.currentTime > 5 ? (video.currentTime - 5) : 0
      } else if (e.code === 'ArrowRight' && video.currentTime !== video.duration) {
        video.currentTime = video.currentTime + 5 > video.duration ? video.duration : video.currentTime + 5
      }
    }
  },
  methods: {
    /**
     * 字幕上传校验
     * @param file
     * @returns {boolean}
     */
    subtitleHandlePreview(file) {
      const fileType = (file.type === '' && file.name.length > 4 ? (file.name.slice(-3) === 'srt' || file.name.slice(-3) === 'ass' || file.name.slice(-3) === 'ssa') : false)
      if (!fileType) {
        Message.error('文件格式仅支持ass,ssa,srt')
      }
      return fileType
    },
    addSubTitle(params) {
      let formData = new FormData()
      formData.append('subtitle', params.file)
      formData.append('id', params.action)
      subtitleUpload(formData).then(res => {
        if (res.code === 200) {
          Message.success('上传成功')
          // for (let i = 0; i < this.videoFileList.length; i++) {
          //   if (this.videoFileList[i].id === res.data.id) {
          //     this.videoFileList[i] = res.data
          //     break
          //   }
          // }
          this.getList()
          params.onSuccess(params)
        } else if (res.code === 500) {
          Message.error(res.msg)
          params.onError(params)
        }
      })
    },
    getHistoryVideo() {
      getHistoryVideoList(this.historyQueryParams).then(res => {
        if (res.code === 200) {
          this.historyVideoList = res.rows
          this.historyTotal = res.total
        }
      })
    },
    //封面
    getHeadImg(src) {
      return src ? (process.env.VUE_APP_BASE_API + src) : ''
    },
    //由id取得播放视频对象
    startSelectVideo(id) {
      getVideoFile(id).then(res => {
        if (res.code === 200) {
          //播放视频
          this.playerLoadVideo(res.data)
          this.nowPlayVideo = res.data
        } else {
          Message.error('未找到视频')
        }
      })
    },
    //由视频对象加载并播放视频,视频格式不同则自动重载视频播放对象
    playerLoadVideo(video, his) {
      let currentTime = 0
      if (his && his.second) currentTime = parseInt(his.second)
      let videoUrl = this.getVideoUrl(video.id)
      //如重新创建播放器
      if (this.player) {
        this.player.destory()
        this.player = null
      }
      let that = this
      let customSetting = []
      let contextmenu = []
      //如果字幕存在
      if (video.subtitleName) {
        //添加字幕字体选择功能
        customSetting.push({
          functions: '字幕字体',
          model: 'select',
          show: true,
          zIndex: 0,
          childConfig: [
            { functions: '默认' },
            { functions: '思源宋体', selected: true },
            { functions: '幼圆' }
          ],
          onToggle: function(data, selected, back) {
            switch (data.functions) {
              case '默认':
                that.subtitle.setFont('Arial')
                selected(data)
                break
              case '幼圆':
                that.subtitle.setFont('YouYuan')
                selected(data)
                break
              default: {
                const font = new FontFace(that.font, 'url(' + that.fontMap[that.font] + ')')
                font.load().then(f => {
                  document.fonts.add(f)
                }).then((e) => {
                  that.subtitle.setFont(that.font)
                  selected(data)
                })
              }
            }
          }
        })
      } else {
        //右键上传字幕功能
        contextmenu.push({
          name: 'copyPlayUrl',
          context: '上传字幕',
          zIndex: 0,
          show: true,
          click: function(close) {
            that.$refs.upload.onChange()
            close()
          }
        })
      }
      this.player = new MuiPlayer({
        container: '#mui-player',
        title: video.fileName,
        src: videoUrl,
        autoplay: true,
        //音量
        volume: 1,
        parse: video.extendedName === 'flv-application/octet-stream' ? {
          type: 'flv',
          loader: Flv, // flv config to：https://github.com/Bilibili/flv.js/blob/HEAD/docs/api.md#flvjscreateplayer
          config: {
            cors: true
          }
        } : (video.extendedName === 'asdfghjkl' ? {
          type: 'hls',
          loader: Hls,
          config: { // hls config to：https://github.com/video-dev/hls.js/blob/HEAD/docs/API.md#fine-tuning
            debug: false
          }
        } : null),
        plugins: [
          new MuiPlayerDesktopPlugin({
            customSetting,
            contextmenu,
            leaveHiddenControls: true
          })
        ],
        custom: {
          footerControls: [
            {
              slot: 'nextMedia', // 对应定义的 slot 值
              position: 'left', // 显示的位置，可选 left、right
              tooltip: '下一集', // 鼠标悬浮在控件上显示的文字提示
              oftenShow: false, // 是否常显示。默认为false，在 mobile 环境下竖屏状态下隐藏，pc环境判下视频容器小于500px时隐藏
              click: function(e) { // 按钮点击事件回调
                that.playNextVideo()
              },
              style: {} // 自定义添加控件样式
            },
            {
              slot: 'openToLocal', // 对应定义的 slot 值
              position: 'left', // 显示的位置，可选 left、right
              tooltip: '在本地打开', // 鼠标悬浮在控件上显示的文字提示
              oftenShow: false, // 是否常显示。默认为false，在 mobile 环境下竖屏状态下隐藏，pc环境判下视频容器小于500px时隐藏
              click: function(e) { // 按钮点击事件回调
                //暂停视频,在本地播放器打开
                that.player.video().pause()
                window.location.href = 'hsmyldkLocalPlayVideo://' + window.location.host + that.getVideoUrl(that.nowPlayVideo.id)
              },
              style: {} // 自定义添加控件样式
            }
          ]
        }
      })
      this.player.on('error', e => {
        Message.error('创建播放器失败')
      })
      this.player.on('ready', e => {
        this.preVideo.preTime = currentTime.toFixed(1)
        let videoDom = this.player.video()
        videoDom.currentTime = currentTime
        if (this.syncVideoInterval != null) clearInterval(this.syncVideoInterval)
        this.syncVideoInterval = setInterval(() => {
          this.syncNowVideo()
        }, 10000)

        if (video.subtitleName) {
          getSubtitle(video.id).then(res => {
            const font = new FontFace(this.font, 'url(' + this.fontMap[this.font] + ')')
            font.load().then(f => {
              document.fonts.add(f)
            }).then((e) => {
              this.subtitle = new H_Subtitle({
                video: videoDom,
                subtitleText: res,
                canvasStyle: 'position: absolute;',
                subtitleStyle: {
                  //字幕颜色
                  fontColor: '#FFFFFF',
                  //字幕背景色
                  // backgroundColor: '#3B3B3B90',
                  // backgroundColor: '#000000',
                  //字幕位置 仅支持百分比,5 就是字幕底边距离video的底边 5% 支持小数
                  subtitlePosition: '5',
                  //字幕字的大小 仅支持百分比,5 就是指字的高度为video高度的5% 支持小数
                  subtitleHeight: '5',
                  //默认的字体样式, 字体大小会自动拼接,这里不要填上
                  font: this.font,
                  // -未实现- 字幕显示样式 [center 居中,left 居左,right 居右]
                  textAlign: 'center',
                  // -未实现- 自动换行
                  autoWrap: true,
                  borderWidth: 3,
                  borderColor: '#000000'
                }
              })
            })
          })
        }
      })
    },
    //拼接视频url
    getVideoUrl(id) {
      return process.env.VUE_APP_BASE_API + '/video/videoFile/getVideo/' + id
    }
    ,
    //播放下一集
    playNextVideo() {
      if (this.videos.length !== this.nowPlayVideo.sort + 1) {
        this.startSelectVideo(this.videos[this.nowPlayVideo.sort + 1].id)
      } else {
        Message.warning('已经是最后一集了')
      }
    }
    ,
    syncNowVideo() {
      //取得视频时间
      let toFixed = parseInt(this.player.video().currentTime.toFixed(1))
      //首先播放进度不是0 且 当播放时间不同或播放的视频不同时向后台同步播放进度
      if (toFixed !== 0 && (this.preVideo.preTime !== toFixed || this.preVideo.id !== this.nowPlayVideo.id)) {
        //刷新数据
        this.preVideo = this.nowPlayVideo
        this.preVideo.preTime = toFixed
        //保存进度至后台
        addHistory({
          videoId: this.preVideo.videoId,
          videoFileId: this.preVideo.id,
          second: toFixed
        }).then(res => {
        })
      }
    }
  }
}
</script>

<style scoped>
.h-center {
  text-align: center;
}

.h-right-box {
  text-align: left;
  background: #F4F4F4;
  margin: 15px;
  padding: 5px;
}

.h-video-radio-box {
  display: inline-block;
  background: #FFFFFF;
  margin: 0 10px 10px 10px;
  text-align: center;
  line-height: 40px;
  font-size: 20px;
  width: 70px;
  height: 40px;
  border: 1px solid #DCDFE6;
  border-radius: 8px;
  cursor: pointer;
  font-family: SourceHanSerifCN, serif;
}

.h-video-radio-box-select {
  border: 1px solid #409eff;
  color: #409eff;
}

@font-face {
  font-family: "SourceHanSerifCN";
  src: url("../assets/fonts/SourceHanSerifCN-SemiBold-7.otf"),
}

.h-box-card {
  margin-top: 10px;
}

.h-card-div {
  display: flex;
}

.h-card-div > div:first-child {
  width: 130px;
  height: 60px;
  background: #FFF;
  margin: 10px 0 10px 0;
}

.h-card-div > div:nth-child(2) {
  margin-left: 20px;
}
</style>
